package com.longcai.cm.api.api4Shopuser;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.longcai.cm.api.response.ShopOrderViewModel;
import com.longcai.cm.auth.Login;
import com.longcai.cm.auth.LoginUser;
import com.longcai.cm.bean.Page;
import com.longcai.cm.bean.R;
import com.longcai.cm.domain.FaMember;
import com.longcai.cm.domain.JaOrder;
import com.longcai.cm.service.FaMemberService;
import com.longcai.cm.service.JaOrderService;
import com.longcai.cm.service.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * @author libingxing
 */
@RestController
@Api(tags = "门店管理员相关api")
@RequestMapping("/api/shop/user")
public class ApiShopUserController {

    @Resource
    private FaMemberService memberService;

    @Resource
    private JaOrderService orderService;

    @Resource
    private RedisService redisService;

    @Login
    @PostMapping("/shopUserList")
    @ApiOperation("员工管理")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "当前页", name = "page", dataType = "int", required = true),
            @ApiImplicitParam(value = "条数", name = "rows", dataType = "int", required = true),
            @ApiImplicitParam(value = "手机号", name = "mobile", dataType = "int", required = true),
            @ApiImplicitParam(value = "是否查询店员 0全部 1只查询店员", name = "mobile", dataType = "int", required = true),
    })
    public R<Page<List<FaMember>>> shopUserList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer rows,
            @RequestParam(defaultValue = "1") Integer ifShopUser,
            @ApiIgnore @LoginUser FaMember member,
            String mobile
    ) {
        final LambdaQueryWrapper<FaMember> wrapper = new LambdaQueryWrapper<>();
        if (ifShopUser == 1) {
            wrapper.eq(FaMember::getShopId, member.getShopId());
        }
        if (StringUtils.isNotBlank(mobile)) {
            wrapper.like(FaMember::getMobile, mobile);
        }
        final long total = memberService.count(wrapper);
        final Page<List<FaMember>> result = new Page<>(page, rows, total);
        wrapper.last(result.convertPage());
        wrapper.orderByDesc(FaMember::getCreatetime);
        final List<FaMember> list = memberService.list(wrapper);
        result.setContent(list);
        return R.success(result);
    }

    @Login
    @PostMapping("/setShopUser")
    @ApiOperation("设置业务员")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id", name = "memberId", dataType = "int", required = true),
            @ApiImplicitParam(value = "业务员标识 1添加 2删除", name = "flag", dataType = "int", required = true),
    })
    public R<Object> setShopUser(
            @ApiIgnore @LoginUser FaMember member,
            String memberId,
            @RequestParam(defaultValue = "1") Integer flag
    ) {
        if (StringUtils.isEmpty(member.getShopId())) {
            return R.error("未找到您的所属门店信息");
        }
        final FaMember shopUser = memberService.getById(memberId);
        if (shopUser == null) {
            return R.error("未找到用户");
        }
        if (flag == 1) {
//            添加
            if (shopUser.getShopRole() == 0) {
//            门店身份 0无 1店主 2店员
                shopUser.setShopRole(2);
                shopUser.setShopId(member.getShopId());
                memberService.updateById(shopUser);
            } else {
                return R.error("该用户已经是店员");
            }
        } else {
            memberService.lambdaUpdate().eq(FaMember::getId, shopUser.getId())
                    .set(FaMember::getShopId, "")
                    .set(FaMember::getShopRole, 0)
                    .update();
        }
        redisService.updateUser(JSON.toJSONString(shopUser), shopUser.getId() + "");
        return R.success();
    }

    @Login
    @PostMapping("/shopOrderList")
    @ApiOperation("商户订单管理")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "当前页", name = "page", dataType = "int", required = true),
            @ApiImplicitParam(value = "条数", name = "rows", dataType = "int", required = true),
            @ApiImplicitParam(value = "订单状态 1待核销 2已核销", name = "status", dataType = "int", required = true),
            @ApiImplicitParam(value = "订单筛选时间", name = "createTime", dataType = "int", required = true),
            @ApiImplicitParam(value = "手机号/订单号", name = "keyword", dataType = "int", required = true),
    })
    public R<ShopOrderViewModel> shopOrderList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer rows,
            @ApiIgnore @LoginUser FaMember member,
            String status, String createTime, String keyword
    ) {
        final ShopOrderViewModel orderViewModel = new ShopOrderViewModel();
        final LambdaQueryWrapper<JaOrder> wrapper = new LambdaQueryWrapper<>();
        final LambdaQueryWrapper<JaOrder> queryWrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JaOrder::getShopId, member.getShopId());
        queryWrapper.eq(JaOrder::getShopId, member.getShopId());
        queryWrapper.between(JaOrder::getOrderStatus, 1, 3);
        if (StringUtils.isNotBlank(status)) {
//            订单状态 0待支付 1待使用 2待评价 3已完成 4已取消 5退款
            if ("2".equals(status)) {
                wrapper.and(w -> w.eq(JaOrder::getOrderStatus, 2).or().eq(JaOrder::getOrderStatus, 3));
            } else {
                wrapper.eq(JaOrder::getOrderStatus, status);
            }
        } else {
            wrapper.between(JaOrder::getOrderStatus, 1, 3);
        }
        if (StringUtils.isNotBlank(createTime)) {
            wrapper.like(JaOrder::getCreateTime, createTime);
            queryWrapper.like(JaOrder::getCreateTime, createTime);
        }
        if (StringUtils.isNotBlank(keyword)) {
            wrapper.like(JaOrder::getContactMobile, keyword).or()
                    .like(JaOrder::getOrderNum, keyword);
            queryWrapper.like(JaOrder::getContactMobile, keyword).or()
                    .like(JaOrder::getOrderNum, keyword);
        }
        final long total = orderService.count(wrapper);
//        流水统计
        final List<JaOrder> incomeList = orderService.lambdaQuery()
                .select(JaOrder::getPayAmount, JaOrder::getOrderStatus)
                .eq(JaOrder::getShopId, member.getShopId())
                .between(JaOrder::getOrderStatus, 2, 3)
                .list();
        if (incomeList.size() > 0) {
            orderViewModel.setTotalIncome(BigDecimal.valueOf(incomeList.stream().mapToDouble(i -> i.getPayAmount().doubleValue()).sum()).setScale(2, RoundingMode.HALF_UP));
        } else {
            orderViewModel.setTotalIncome(new BigDecimal(0));
        }
        final List<JaOrder> countList = orderService.list(queryWrapper);
        if (countList.size() > 0) {
            orderViewModel.setOrderTotal(countList.size());
            orderViewModel.setOrderUnchecked(countList.stream().filter(o -> o.getOrderStatus() == 1).count());
            orderViewModel.setOrderChecked(countList.stream().filter(o -> o.getOrderStatus() == 2 || o.getOrderStatus() == 3).count());
        }
        final Page<List<JaOrder>> result = new Page<>(page, rows, total);
        wrapper.last(result.convertPage());
        wrapper.orderByDesc(JaOrder::getCreateTime);
        final List<JaOrder> list = orderService.list(wrapper);
        result.setContent(list);
        orderViewModel.setOrderList(result);
        return R.success(orderViewModel);
    }

    @Login
    @PostMapping("/checkOrder")
    @ApiOperation("核销订单")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "订单id", name = "orderId", dataType = "int", required = true)
    })
    public R<Object> checkOrder(
            @ApiIgnore @LoginUser FaMember member,
            String orderId
    ) {
        orderService.checkOrder(orderId, member);
        return R.success();
    }
}
